package com.thunisoft.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * @title NettyHttpHelloworldServer.java
 * @package com.thunisoft.netty.http
 * @projectName spring.boot
 * @author yzj
 * @date 2019年10月8日 下午3:01:34
 */
public class NettyHttpHelloworldServer {
	
	private int port;
	
	public NettyHttpHelloworldServer(int port) {
	    this.port = port;
	  }

	  public void startUp() {
	    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
	    EventLoopGroup workerGroup = new NioEventLoopGroup();
	    try {
	      ServerBootstrap b = new ServerBootstrap();
	      b.option(ChannelOption.SO_BACKLOG, 1024);
	      b.group(bossGroup, workerGroup)
	          .channel(NioServerSocketChannel.class)
	          .childHandler(
	              new ChannelInitializer<SocketChannel>() {
	                @Override
	                protected void initChannel(SocketChannel socketChannel) throws Exception {
	                  socketChannel.pipeline()
	                      .addLast(new HttpServerCodec()) //请求解码器和响应编码器，等价于下面两行
//	                      .addLast(new HttpRequestDecoder()) //请求解码器
//	                      .addLast(new HttpResponseEncoder()) //响应编码器
	                      .addLast(new NettyHttpHelloWorldServerHandler());
	                }
	              }

	          );
	      Channel ch = b.bind(port).sync().channel();
	      System.out.println(String.format("服务已经启动，端口号为：%s", port));
	      ch.closeFuture().sync();
	    } catch (Exception e) {
	      e.printStackTrace();

	    } finally {
	      //关闭服务
	      bossGroup.shutdownGracefully();
	      workerGroup.shutdownGracefully();
	    }
	  }
	public static void main(String[] args) {
		new NettyHttpHelloworldServer(9998).startUp();
	}
}
